﻿using PLCS.Application.Contracts.HisTaskApp.Dtos;
using PLCS.Application.Contracts.InterfaceApp;
using PLCS.Application.Contracts.InterfaceApp.Dtos;
using PLCS.Application.Contracts.Params;
using PLCS.Domain.Logs;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.InterfaceLogApp;

public class InterfaceLogAppService : CrudAppService<InterfaceLog, InterfaceLogDto, Guid, PagedResultRequestDto, InterfaceLogDto>, IInterfaceLogAppService
{
    public InterfaceLogAppService(IRepository<InterfaceLog, Guid> repository) : base(repository)
    {
    }

    public async Task<PagedResultDto<InterfaceLogDto>> GetListBySearchAsync(PagedResultRequestDto input, string? startTime, string? endTime, string? requestSide, string? responseSide)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);

        bool isStartTime = DateTime.TryParse(startTime, out DateTime StartDateTime);
        query = query.WhereIf(isStartTime, x => x.CreationTime > StartDateTime);
        bool isEndTime = DateTime.TryParse(endTime, out DateTime EndDateTime);
        query = query.WhereIf(isEndTime, x => x.CreationTime < EndDateTime);
        query = query.WhereIf(!string.IsNullOrEmpty(requestSide), x => x.RequestSide == requestSide)
            .WhereIf(!string.IsNullOrEmpty(responseSide), x => x.ResponseSide == responseSide);
        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplySorting(query, input);
        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<InterfaceLogDto>(
            totalCount,
            entityDtos
        );
    }
}